//const {
//  createWriteStream,
//} = require('node:fs');

import { open } from 'node:fs/promises';
import { createWriteStream } from 'node:fs';

import {
  scryptSync,
  createDecipheriv,
} from 'node:crypto';

import { Buffer } from 'node:buffer';
import { createInterface } from 'node:readline';

const algorithm = 'aes-256-cbc';
let password = 'Password used to generate key';
// Use the async `crypto.scrypt()` instead.

// The IV is usually passed along with the ciphertext.
//const iv = Buffer.alloc(16, 0); // Initialization vector.

const rl = createInterface({
  input: process.stdin,
  output: process.stdout
});
rl.question('请输入：', (answer) => {
      password = answer.trim();
      decrypto();
      rl.close();
    });

async function decrypto(){
    console.log('开始解密：'+process.argv[2]);
    const key = scryptSync(password, 'salthell', 32);
    const f = await open(process.argv[2]);
    const output = await createWriteStream('out.txt');
    let num = 0;
    let iv = Buffer.alloc(16,0);
    await f.read(iv);
    let decipher = createDecipheriv(algorithm, key, iv);
    //console.log(`iv:${iv}`);
    const input = f.createReadStream({ start: 16 });
    input.pipe(decipher).pipe(output);
}

